package com.pktechan.api.tradeOrderStatus;


import com.pktechan.api.entity.StatusFlow;
import com.pktechan.api.entity.TradeOrder;
import com.pktechan.api.enumeration.ChangeTradeOrderStatusEnum;
import com.pktechan.api.enumeration.StatusFlowTypeEnum;
import com.pktechan.api.exception.CustomException;
import com.pktechan.api.service.StatusFlowService;
import com.pktechan.api.service.TradeOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @program: cloudfloating
 * @description: 改变订单状态基类
 * @author: qx.zhang
 * @create: 2021-03-15 11:27
 **/
public class BaseChangeTradeOrderState {
    private final static Logger logger = LoggerFactory.getLogger(BaseChangeTradeOrderState.class);

    @Resource(name = "statusFlowService")
    private StatusFlowService statusFlowService;

    @Resource(name = "tradeOrderService")
    private TradeOrderService tradeOrderService;

    /**
     * 插入状态变化记录
     *
     * @param tradeOrderId
     * @param stateOld
     * @param stateCur
     * @param exeRemark
     */
    protected void addTradeOrderStateFlow(Integer tradeOrderId, Integer stateOld, Integer stateCur,
                                          Integer custId, String exeRemark) {
        StatusFlow statusFlow = new StatusFlow();
        statusFlow.setBusinessType(StatusFlowTypeEnum.ORDER.getCode());
        statusFlow.setBusinessNo(tradeOrderId);
        statusFlow.setStateOld(stateOld);
        statusFlow.setStateCur(stateCur);
        statusFlow.setExeCustId(custId);
        statusFlow.setExeRemark(exeRemark);
        statusFlowService.save(statusFlow);
    }

    /**
     * 获取改变订单状态的行为对象
     *
     * @param changeTradeOrderStatusEnum
     * @return
     */
    public static ChangeTradeOrderState getChangeContractState(ChangeTradeOrderStatusEnum changeTradeOrderStatusEnum) {
        Map<ChangeTradeOrderStatusEnum, ChangeTradeOrderState> map = ChangeTradeOrderStateSingleton.getInstance();
        ChangeTradeOrderState changeTradeOrderState = map.get(changeTradeOrderStatusEnum);
        return changeTradeOrderState;
    }

    /**
     * 订单数据校验
     *
     * @param tradeOrderId
     * @return
     */
    protected TradeOrder tradeOrderDataValidation(Integer tradeOrderId) {
        TradeOrder tradeOrder = tradeOrderService.getById(tradeOrderId);
        if (tradeOrder == null) {
            logger.debug("订单ID为" + tradeOrderId + "对应的订单不存在");
            throw new CustomException("订单不存在");
        }
        return tradeOrder;
    }

    /**
     * 更新订单状态
     *
     * @param jobInviteId
     * @param status
     */
    protected void updateTradeOrder(Integer jobInviteId, Integer status) {
        TradeOrder tradeOrder = new TradeOrder();
        tradeOrder.setId(jobInviteId);
        tradeOrder.setStatus(status);
        tradeOrderService.update(tradeOrder);
    }

}
